package com.chcit.mobile.mvp.common.model;

import android.app.Application;

import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.mvp.common.contract.HomeContract;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.BaseData;
import com.chcit.mobile.mvp.entity.ChildrenBean;
import com.chcit.mobile.mvp.entity.TaskMenuBean;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.ActivityScope;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;


@ActivityScope
public class HomeModel extends BaseModel implements HomeContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public HomeModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

    @Override
    public Observable<List<ChildrenBean>> getMenues() {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .request(HttpMethodContains.Home.MENU_QUERY)
                .map( jsonObject -> {
                   boolean success = jsonObject.getBoolean("success");
                    if(success){
                        return jsonObject.getJSONObject("data").getJSONArray("children").toJavaList(ChildrenBean.class);
                    }else{
                        throw new Exception("请求失败: "+jsonObject.getString("msg"));
                    }

                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<List<TaskMenuBean>> getTaskMenues() {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .queryWaitDoc()
                .map(result->{
                    if(result.isSuccess()){
                        return result.getRows().toJavaList(TaskMenuBean.class);
                    }else{
                        return new ArrayList<TaskMenuBean>();
                    }

        }).subscribeOn(Schedulers.io());
    }
}